package br.com.exemplo.vendas.negocio.dao ;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;

import br.com.exemplo.vendas.negocio.entity.Cliente;
import br.com.exemplo.vendas.negocio.entity.Usuario;

public class ClienteDAO extends GenericDAO<Usuario>
{
	public ClienteDAO( EntityManager em )
	{
		super( em ) ;
	}

	public ClienteDAO( )
	{
		super( Persistence.createEntityManagerFactory( "Vendas" ).createEntityManager( ) ) ;
	}

	public List<Cliente> listarClientes()
	{
		List<Cliente> retorno = new ArrayList<Cliente>() ;

		@SuppressWarnings("rawtypes")
		List queryResult = null;
		try
		{
			Query query = em.createNativeQuery("SELECT c.id, c.nome FROM Usuario as c INNER JOIN Compra as cm on " +
					"(c.id = cm.id_cliente)");
			queryResult = query.getResultList();
		}
		catch (Exception e)
		{
			if (debugInfo)
			{
				e.printStackTrace( ) ;
			}
		}
		
		if (queryResult != null && queryResult.size() > 0){
			for (int i = 0; i < queryResult.size() ; i++) {
				Object array[] = (Object[]) queryResult.get(i);
				Cliente cliente = new Cliente();	
				cliente.setId((Integer) array[0]);
				cliente.setNome((String) array[1]);
				
				retorno.add(cliente);
			}
			return retorno ;
		}
		else{
			return null;
		}
	}

}